package net.xujialiang.XTestRPA.Repository.RPA;

import net.xujialiang.XTestRPA.Entity.RPA.XRPATask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface RPATaskRepository extends CrudRepository<XRPATask, Integer> {
    List<XRPATask> findAllByGroupIDAndTtc(String GroupID, String ttc);
    List<XRPATask> findAllByTtc(String ttc);
    Page<XRPATask> findByTtc(String ttc, Pageable page);
    Page<XRPATask> findByGroupID(String GroupID, Pageable page);

    @Query(value = "SELECT DISTINCT RPATASK.ID FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE GROUPID = ?1 and TTC = ?2 order by RPATASK.mOrder desc,RPATASK.mOrder desc",
            countQuery = "SELECT count(RPATASK.ID) FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE GROUPID = ?1 and TTC = ?2",
            nativeQuery = true)
    Page<Integer> findTaskIDsByGroupID(String GroupID, String ttc, Pageable pageable);

    @Query(value = "SELECT DISTINCT RPATASK.ID FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE TAGID IN ?1 and TTC = ?2 order by RPATASK.mOrder desc,RPATASK.mOrder desc",
            countQuery = "SELECT count(RPATASK.ID) FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE TAGID IN ?1 and TTC = ?2",
            nativeQuery = true)
    Page<Integer> findTaskIDsByTagIDS(List<String> tagId, String ttc, Pageable pageable);

    @Query(value = "SELECT DISTINCT RPATASK.ID FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE GROUPID = ?1 and TAGID IN ?2 and TTC = ?3 order by RPATASK.mOrder desc,RPATASK.mOrder desc",
            countQuery = "SELECT count(RPATASK.ID) FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE GROUPID = ?1 and TAGID IN ?2 and TTC = ?3",
            nativeQuery = true)
    Page<Integer> findTaskIDsByGroupIDAndTagIDS(String GroupID, List<String> tagId, String ttc, Pageable pageable);

    @Query(value = "select * from RPATASK where id in (SELECT DISTINCT RPATASK.ID FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE (:groupID is null or RPATASK.GROUPID = :groupID) and (:taskName is null or RPATASK.TASKNAME = :taskName) and (:tagIds is null or TAGID IN (:tagIds)) and (RPATASK.TTC = :ttc) ) order by mOrder desc,ID desc",
            countQuery = "SELECT count(RPATASK.ID) FROM RPATASK LEFT JOIN TASKANDTAG on TASKANDTAG.TASKID = RPATASK.TASKID WHERE GROUPID = :groupID and TTC = :ttc and TASKNAME= :taskname and TAGID IN (:tagIds)",
            nativeQuery = true)
    Page<XRPATask> findByTaskNameAndGroupIdAndByTagIds(String groupID, String taskName, List<String> tagIds, String ttc, Pageable pageable);
}